package cn.wang.web;

import cn.wang.entity.log.LoginLog;
import cn.wang.entity.sysadmin.User;
import cn.wang.service.login.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.omg.IOP.ServiceContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;

import java.sql.Date;
import java.sql.Time;

public class LoginAction extends ActionSupport {
	private String username;
	private String password;
	@Autowired
	private LoginService loginService;
	public String login() {

		//认证功能
		if (username != null && !username.isEmpty() && password != null&&! password.isEmpty()) {
			try{
				//获取 shiro中的 subject () 获取其中对像存入session
				Subject subject = SecurityUtils.getSubject();
				//将表单数据存入token中 令牌
				UsernamePasswordToken token = new UsernamePasswordToken(username, password);
				subject.login(token);
				//获取其中对像存入session
				User user = (User) subject.getPrincipal();
				ServletActionContext.getRequest().getSession().setAttribute("_CURRENT_USER", user);
			}catch (Exception e){
				return "login";
			}

		}else{
			return "login";
		}
		//获取的是本地的IP地址 //PC-20140317PXKX/192.168.1.147
		//记录登录日志
		InetAddress address = null;
		try {
			address = InetAddress.getLocalHost();
		} catch ( UnknownHostException e ) {
			e.printStackTrace();
		}
		String hostAddress = address.getHostAddress();
		LoginLog loginLog=new LoginLog();
		loginLog.setIpAddress(hostAddress);
		loginLog.setLoginName(username);
		loginLog.setLoginTime(new Time(System.currentTimeMillis()));
		loginService.logAdd(loginLog);
		return "success";
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
